package com.szrt.javaweb;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * http://localhost:8080/mvn-JavaWeb-Cookie/login.do
 *
 */
public class LoginServlet extends HttpServlet {
	
	private static final long serialVersionUID = -3699292859687024137L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//在进入 login.jsp的页面之前 如果request里面有cookie  key=szrt value=123456 直接跳到success.jsp
		
		String zxx          = request.getParameter("method");
		String username     = request.getParameter("username");
		String password     = request.getParameter("password");
		String isCheckedabc = request.getParameter("isCheckedabc");
		
		
		request.getSession().setAttribute("username", username);
		request.getSession().setAttribute("password", password);
		request.getSession().setAttribute("isCheckedabc", isCheckedabc);
		
		
		//zx 注销
		if(null != zxx && zxx.equals("zx")){
			//把本地的cookie立即删除
			Cookie[] cookies = request.getCookies(); 
			if(null != cookies){
				for(Cookie c : cookies){
					String key   = c.getName();
					String value = c.getValue();
					if(key.equals("szrt") && value.equals("123456")){
						//删除cookie
						c.setMaxAge(0);
						response.sendRedirect("login.jsp");
						return;
					}
				}
			}
			
			
		}
		
		
		// zxx 代表  登录
		if(null != zxx && zxx.equals("zxx")){
			
			//说明是点击了登录页面的 登录按钮进来的
			//知道用户是否点击了保存十天
			if("on".equals(isCheckedabc)){
				//保存 cookie到磁盘中
				//1 创建1个javax.servlet.http.Cookie类的对象
				Cookie cookie = new Cookie("szrt","123456");
				
				//10天
				cookie.setMaxAge(10*24*60*60);
				
				//2 调用response的addCookie方法将cookie发送给浏览器
				response.addCookie(cookie);
				response.sendRedirect("success.jsp");
				return;
				
			}else{
				response.sendRedirect("success.jsp");
				return;
			}
		}
		
		
		//说明是通过 http://localhost:8080/mvn-JavaWeb-Cookie/login.do
		Cookie[] cookies = request.getCookies(); 
		int counter =0;
		if(null != cookies){
			for(Cookie c : cookies){
				String key   = c.getName();
				String value = c.getValue();
				if(key.equals("szrt") && value.equals("123456")){
					//说明有cookie
					counter++;
					
					//把用户名和密码放到session中去
					request.getSession().setAttribute("username", key);
					request.getSession().setAttribute("password", value);
					response.sendRedirect("success.jsp");
					return;
				}
			}
		}
		
		if(null == cookies || counter==0 ){
			//说明没有cookie
			response.sendRedirect("login.jsp");
			
		}
		
	}

}
